package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.DESUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2021-12-22
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    /**
     * 管理员用户登陆
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //1.判断是否有值
        if (loginDto == null || StringUtils.isEmpty(loginDto.getName()) || StringUtils.isEmpty(loginDto.getPassword())) {
            //返回缺少参数的结果
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.根据账号查询，是否存在该用户
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName, loginDto.getName());
        AdUser one = this.getOne(queryWrapper);
        //判断one是否为空
        if (one == null) {
            //返回账号错误的结果
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //3.再根据密码进行查询进行判断，密码需要经过处理
        String pwdStr = loginDto.getPassword() + one.getSalt();
        String userEnterPwdEncodedStr = DigestUtils.md5DigestAsHex(pwdStr.getBytes());

        //判断密码是否正确
        if (!StringUtils.equals(userEnterPwdEncodedStr, one.getPassword())) {
            //返回密码错误的结果
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);

        }
        //4.制作token,需要进行脱敏操作
        HashMap<String, Object> claimMaps = new HashMap<>();
        claimMaps.put("userId", one.getId());
        claimMaps.put("userName", one.getName());
        String token = AppJwtUtil.getToken(claimMaps);

        //5.返回结果,需要进行脱敏处理
        one.setPhone(null);
        one.setSalt(null);
        one.setPassword(null);

        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("user", one);
        resultMap.put("token", token);
        return ResponseResult.okResult(resultMap);

    }
}
